package com.tbl.modules.wms2.controller.workorder;

import cn.hutool.db.handler.HandleHelper;
import com.ctc.wstx.util.StringUtil;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms2.dao.workorder.WorkOrderDAO;
import com.tbl.modules.wms2.entity.ordermanage.asn.AsnHeaderEntity;
import com.tbl.modules.wms2.entity.purchasein.OutSourcingPOEntity;
import com.tbl.modules.wms2.entity.purchasein.PurchaseOrderEntity;
import com.tbl.modules.wms2.entity.workorder.ReceiveOrderEntity;
import com.tbl.modules.wms2.entity.workorder.SaveWorkOrderEntity;
import com.tbl.modules.wms2.entity.workorder.WorkOrderEntity;
import com.tbl.modules.wms2.service.purchasein.PurchaseOrderService;
import com.tbl.modules.wms2.service.workorder.WorkOrderService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import oracle.sql.NUMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购订单
 * 入库管理
 *
 * @author DASH
 */
@Controller
@RequestMapping(value = "/ycl/workorder/WorkOrder")
public class WorkOrderController extends AbstractController {


    @Autowired
    private RoleService roleService;

    @Autowired
    private WorkOrderService workOrderService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    /**
     * 跳转编辑页
     *
     * @return
     */
    @RequestMapping(value = "/addWorkorder")
    public ModelAndView addWorkorder(String rcvId) {
        ModelAndView mv = this.getModelAndView();
//        ReceiveOrderEntity addEntity = new ReceiveOrderEntity();
//        addEntity = workOrderService.getRcvInfoByRcvId(Long.parseLong(rcvId));
//        mv.addObject("addEntity", addEntity);
        mv.setViewName("techbloom2/outsourcing/order/add");
        return mv;
    }

    /**
     * EBS的委外加工-新增接受单。对应到WMS中委外加工的接受按钮功能
     *
     * @return
     */
    @RequestMapping(value = "/receiveWorkOrder", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, String> receiveWorkOrder(@RequestBody SaveWorkOrderEntity saveWorkOrderEntity) {
        Map<String, Object> paramsMap = new HashMap<>();
        //操作类型type: save  commit；根据type获取对应的存储过程
        String type = saveWorkOrderEntity.getType();
        //--接收数量
        paramsMap.put("rcvQuantity", saveWorkOrderEntity.getRcvQuantity());
        //--费用接收子库
        paramsMap.put("subinventory", saveWorkOrderEntity.getSubinventory());
        //--费用接收货位ID
        paramsMap.put("locatorId", saveWorkOrderEntity.getLocatorId());
        //--委外加工头ID（从EBS查询订单时带出）
        paramsMap.put("poId", saveWorkOrderEntity.getPoId());
        //--库存组织ID（从EBS查询订单时带出）
        paramsMap.put("organizationId", saveWorkOrderEntity.getOrganizationId());
        //--完工物料ID（通过EBS订单查出）
        paramsMap.put("wxItemId", saveWorkOrderEntity.getWxItemId());
        //--接收行ID 空
        paramsMap.put("rcvId", saveWorkOrderEntity.getRcvId());
        //--委外加工物料(废品) 空
//        paramsMap.put("itemId", saveWorkOrderEntity.getItemId());
        paramsMap.put("itemId", saveWorkOrderEntity.getMaterialId());

        Map<String, String> resultMap = new HashMap<>();

        if ("save".equals(type)) {
            workOrderService.createReceive(paramsMap); //对应的存储过程apps.cux_wms_outside_pkg.create_rcv
        }
        if ("commit".equals(type)) {
            workOrderService.receiveProcess(paramsMap); //对应的存储过程apps.cux_wms_outside_pkg.rcv_process
        }

        if (paramsMap.containsKey("retCode")) {
            if (paramsMap.get("retCode").toString().equals("S")) {
                resultMap.put("retCode", "success");
                resultMap.put("retMess", "执行成功");
            } else {
                resultMap.put("retCode", "error");
                resultMap.put("retMess", "执行失败");
            }
        }
        return resultMap;
    }

    /**
     * EBS的委外加工-工单保存
     *
     * @return
     */
    @RequestMapping(value = "/createComplete", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, String> createComplete(@RequestBody List<WorkOrderEntity> workOrderEntityList) {
        Map<String, String> resultMap = new HashMap<>();
        for (WorkOrderEntity line : workOrderEntityList) {
            //操作类型type: save  commit；根据type获取对应的存储过程
            String type = line.getType();

            Map<String, Object> validateMap = new HashMap<>();
            validateMap.put("organizationId", line.getOrganizationId());//库存组织ID
            validateMap.put("ftItemId", line.getFtItemNum());//消耗物料ID
            validateMap.put("ftSubCode", line.getFtSubinventoryDesc());//发料子库
            validateMap.put("ftLocatorId", line.getFtComponentLocatorId());//发料货位
            validateMap.put("qty ", line.getFtcompletedQty());//完工数量

            Map<String, Object> createOrderMap = new HashMap<>();
            createOrderMap.put("rcvId", line.getRcvId());
            createOrderMap.put("completeItemId", line.getCompleteItemId());
            createOrderMap.put("completeSub", line.getCompleteSub());
            createOrderMap.put("completeLocatorId", line.getCompleteLocatorId());
            createOrderMap.put("completeQty", line.getCompleteQty());
            createOrderMap.put("fyItemId", line.getFyItemId());
            createOrderMap.put("fySub", line.getFySub());
            createOrderMap.put("fyLocatorId", line.getFyComponentLocatorId());
            createOrderMap.put("fyQty", line.getFyComponentQty());
            createOrderMap.put("ftItemId", line.getFtItemNum());
            createOrderMap.put("ftSub", line.getFtSubinventoryDesc());
            createOrderMap.put("ftLocatorId", line.getFtComponentLocatorId());
            createOrderMap.put("ftQty", line.getFtcompletedQty());
            createOrderMap.put("organizationId", line.getOrganizationId());
            createOrderMap.put("wipEntityId", line.getWipEntityId());
            createOrderMap.put("vendorLot", line.getVendorLot());
            createOrderMap.put("vendorFtLot", line.getVendorFtLot());
            createOrderMap.put("wipComId", line.getWipComId());
            try {
                if ("save".equals(type)) {
                    workOrderService.createComplete(createOrderMap); //对应的存储过程apps.cux_wms_outside_pkg.create_rcv
                    resultMap.put("retCode", createOrderMap.get("retCode").toString());
                    resultMap.put("retMess", createOrderMap.get("retMess").toString());
                }
                if ("commit".equals(type)) {
                    workOrderService.validateQuantity(validateMap); //对应的存储过程apps.cux_wms_outside_pkg.create_rcv
                    if ("S".equals(validateMap.get("retCode"))) {
                        workOrderService.completeProcess(createOrderMap); //对应的存储过程apps.cux_wms_outside_pkg.create_rcv
                        resultMap.put("retCode", createOrderMap.get("retCode").toString());
                        resultMap.put("retMess", createOrderMap.get("retMess").toString());
                    } else {
                        resultMap.put("retCode", validateMap.get("retCode").toString());
                        resultMap.put("retMess", validateMap.get("retMess").toString());
                    }
                }
            } catch (Exception e) {
            }
        }

        return resultMap;
    }

    /**
     * 通过订单ID获取订单信息
     *
     * @return
     */
    @RequestMapping(value = "/getOutSourcingPOByPoId")
    @ResponseBody
    public OutSourcingPOEntity getOutSourcingPOByPoId(Long poId) {
        return workOrderService.getOutSourcingPOByPoId(poId);
    }

    /**
     * 获取废料信息
     *
     * @return
     */
    @RequestMapping(value = "/getFtInfo",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getFtInfo(@RequestParam("code") String code) {
        Map<String,Object> paramMap = getAllParameter();
        paramMap.put("code",code);

        return workOrderService.getFtInfo(paramMap);

    }

    /**
     * 通过订单ID获取接收单List
     *
     * @return
     */
    @RequestMapping(value = "/getRcvListByPoId")
    @ResponseBody
    public List<ReceiveOrderEntity> getRcvListByPoId(Long poId) {
        return workOrderService.getRcvListByPoId(poId);
    }

    /**
     * 通过接收单ID获取工单List
     *
     * @return
     */
    @RequestMapping(value = "/getWorkOrderListByRcvId")
    @ResponseBody
    public List<WorkOrderEntity> getWorkOrderListByRcvId(Long rcvId) {
        return workOrderService.getWorkOrderListByRcvId(rcvId);
    }

    /**
     * 通过接收单ID获取接收单信息
     *
     * @return
     */
    @RequestMapping(value = "/getRcvInfoByRcvId")
    @ResponseBody
    public ReceiveOrderEntity getRcvInfoByRcvId(Long rcvId) {
        return workOrderService.getRcvInfoByRcvId(rcvId);
    }

    /**
     * 通过视图查看是否可以退回
     *
     * @return
     */
    @RequestMapping(value = "/getReceiveOrderState")
    @ResponseBody
    public String getReceiveOrderState(Long rcvId) {
        return workOrderService.getReceiveOrderState(rcvId);
    }

    /**
     * 委外退回
     *
     * @return
     */
    @RequestMapping(value = "/returnProcess")
    @ResponseBody
    public Map<String, String> returnProcess(Long rcvId) {
        Map<String,String> resultMap = new HashMap<>();
        String state = workOrderService.getReceiveOrderState(rcvId);
        if("RECEIVE".equals(state) || "COMPLETE".equals(state)){
            workOrderService.returnProcess(rcvId);
        }else{
            resultMap.put("retCode","error");
            resultMap.put("retMess","当前状态不允许退回");
        }
        return resultMap;
    }

    /**
     * 通过组织Id获取费用子库描述
     *
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/getDescriptionByOrgId")
    @ResponseBody
    public List<Map<String, Object>> getDescriptionByOrgId(Long orgId) {
        return workOrderService.getDescriptionByOrgId(orgId);
    }

    /**
     * 通过费用子库描述获取库位列表
     *
     * @param description
     * @return
     */
    @RequestMapping(value = "/getLocatorListByDesc")
    @ResponseBody
    public List<Map<String, Object>> getLocatorListByDesc(String description, String description2) {
        Map paramsMap = new HashMap();
        paramsMap.put("description", description);
        paramsMap.put("description2", description2);
        return workOrderService.getLocatorListByDesc(paramsMap);
    }

//    /**
//     * 弹出到新增/编辑页面
//     *
//     * @param id
//     * @return ModelAndView
//     */
//    @RequestMapping(value = "/toDeliveryOrderEdit")
//    @ResponseBody
//    public ModelAndView toAdd(Long id, WebRequest request) {
//        String workOrderIds = request.getParameter("workOrderIds");
//        ModelAndView mv = this.getModelAndView();
//        mv.setViewName("techbloom2/workorder/deliveryOrderEdit");
//        mv.addObject("workOrderIds", workOrderIds);
//
//        Map<String, Object> paramsMap = new HashMap<>(1);
//        paramsMap.put("woLineIds", workOrderIds);
//        List<WorkOrderEntity> pageList = workOrderDAO.getPageList(
//                new Page(1, 999),
//                paramsMap);
//        mv.addObject("vendorName", pageList.get(0).getSupplierName());
////        mv.addObject("edit", id != null && id != EmumConstant.carState.INSTORAGING.getCode().longValue() ? EmumConstant.carState.OUTSTORAGING
////                : EmumConstant.carState.INSTORAGING);
////        mv.addObject("warehouse", checkService.findById(id));
////        mv.addObject("warehouseAreaList" , carService.selectWarehouseArea());
//        return mv;
//    }
//
//    /**
//     * 保存
//     *
//     * @param
//     * @return Map<String, Object>
//     */
//    @RequestMapping(value = "/save")
//    @ResponseBody
//    public Map<String, Object> save(CheckEntity checkEntity) {
//        Map<String, Object> map = new HashMap<>(2);
////        car.setWarehouseArea(car.getWarehouseArea().replaceAll("\\d+",""));
////        boolean result = checkService.save(checkEntity);
////        map.put("result", result);
////        map.put("msg", result ? "保存成功！" : "保存失败！");
//        return map;
//    }
//
//    /*
//     * 跳转Grid列表页
//     *
//     * @return
//     */
//    @RequestMapping(value = "/toList")
//    public ModelAndView toRewindList() {
//        ModelAndView mv = this.getModelAndView();
//        mv.addObject("operationCode", roleService.selectOperationByRoleId(2L, MenuConstant.warehouselist));
//        mv.setViewName("techbloom2/workorder/workorder/list");
//        return mv;
//    }
//
//    /**
//     * 获取Grid列表数据
//     *
//     * @return Map<String, Object>
//     */
//    @RequestMapping(value = "/list")
//    @ResponseBody
//    public Map<String, Object> list() {
//
//        Map<String, Object> paramsMap = getAllParameter();
//        List<WorkOrderEntity> pageList = workOrderDAO.getPageList(
//                new Page(
//                        Integer.parseInt((String) paramsMap.get("page")),
//                        Integer.parseInt((String) paramsMap.get("limit"))),
//                paramsMap);
//        Map<String, Object> map = new HashMap<>(4);
//        map.put("code", 0);
//        map.put("msg", null);
//        map.put("count", pageList.size());
//        map.put("data", pageList);
//        return map;
//    }
//
//    @RequestMapping(value = "/listByIds")
//    @ResponseBody
//    public Map<String, Object> listByIds() {
//
//        Map<String, Object> paramsMap = getAllParameter();
//        List<WorkOrderEntity> pageList = workOrderDAO.selectBatchIds(StringUtils.stringToList((String) paramsMap.get("workOrderIds")));
//        Map<String, Object> map = new HashMap<>(4);
//        map.put("code", 0);
//        map.put("msg", null);
//        map.put("count", pageList.size());
//        map.put("data", pageList);
//        return map;
//    }
//
//
//    /**
//     * 跳转编辑页
//     *
//     * @return
//     */
//    @RequestMapping(value = "/toEdit")
//    public ModelAndView toDetail(Long id) {
//        String ids = request.getParameter("ids");
//        ModelAndView mv = this.getModelAndView();
//        mv.addObject("operationCode", roleService.selectOperationByRoleId(2L, MenuConstant.warehouselist));
//        mv.setViewName("techbloom2/workorder/workOrder/edit");
//        return mv;
//    }


}
